import Vue from 'vue';
import InsPortalDefApi from './insPortalDef';
import InsAppCollectApi from './insAppCollect'
import extendPortal from "@/api/portal/core/extendPortal";
import moment from "moment";
import InAppAdd from "@/views/modules/portal/core/InAppAdd"
import {Util} from '@lowcode/jpaas-common-lib';
import {mapState} from "vuex";
import miniFront from "@/layouts/miniFront/miniFront";
import ShareFunction from "@/assets/js/ShareFunction";
import { getState,getAuthorizeUri } from "@public/public";

import {I18Parse,CommonLang,TokenUtil} from '@lowcode/jpaas-common-lib';
import portalApiLang from '../../../locales/lang/impl/portal/portalApiLang';
let lang = portalApiLang.portalApi;
let comLang= CommonLang;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang,langKey, text);
}

/**
 * 加载表单
 */
var loadingComponent = {
    template: "<div>"+i18n('loadingData','正在加载数据')+"</div>"
};

var customColumnComponet = Vue.component('custom-column-list', {

    template: "",
    mixins: [extendPortal,miniFront,ShareFunction],
    data() {
        return {
            colId: "",
            insColumnDef: {},
            data: [],

            //这个是TAB的组件才使用到
            currentKey: 0,

            loading: false,
            menu:{}
        }
    },
    computed: {
        ...mapState({
            menus: state => state.appSetting.menus,
            appId: state => state.appSetting.appId,
        })
    },
    methods: {
        getImgPath(fileId,isScale) {
            var accessToken = TokenUtil.getToken();
            if(isScale){
                return `/api/api-system/system/core/sysFile/downloadScale/${fileId}?accessToken=` + accessToken;
            }else {
                return `/api/api-system/system/core/sysFile/download/${fileId}?accessToken=` + accessToken;
            }
        },
        changeKey(key) {
            this.currentKey = key;
        },
        /**
         * 平台内部菜单跳转
         * @param url
         * @param newWin 新窗口
         */
        moreUrl(url, newWin) {
            if (url) {
                if (newWin) {
                    var portalUrl = window.localStorage.getItem('portalUrl');
                    if (portalUrl) {
                        url = portalUrl + url;
                    } else {
                        url = "/jpaas" + url;
                    }
                    window.open(url);
                } else {
                    this.handUrlClick(url);
                }
            } else {
                var typeName = this.insColumnDef.typeName;

                if ("TabBel" == typeName) {
                    var insColumnDef = this.data[this.currentKey].insColumnDef;
                    var settingObj = JSON.parse(insColumnDef.setTing);
                    if (settingObj.dataUrl) {
                        this.handUrlClick(settingObj.dataUrl);
                    }
                } else {
                    var settingObj = JSON.parse(this.insColumnDef.setTing);
                    if (settingObj.dataUrl) {
                        this.handUrlClick(settingObj.dataUrl);
                    }
                }
            }
        },
        refresh() {
            var typeName = this.insColumnDef.typeName;
            //当数据是TAB的情况
            if ("TabBel" == typeName) {
                var insColumnDef = this.data[this.currentKey].insColumnDef;
                //在tab的容器必须为 innerLayout
                //<portal-layoutview ref="innerLayout"  :insColumnDef="obj.insColumnDef"></portal-layoutview>
                var aryTabs = this.$refs.innerLayout;
                var tab = aryTabs[this.currentKey];
                tab.formVm.loadColumn();
            } else {
                this.loadColumn();
            }
        },
        loadData() {
            this.loading = true;
            //如果appId有值
            if(this.appId){
                InsPortalDefApi.getDataByColIdAndAppId(this.colId,this.appId).then(res => {
                    //InsPortalDefApi.getDataByColId(this.colId).then(res => {
                    this.data = res;
                    this.loading = false;
                });
            }else{
                InsPortalDefApi.getDataByColId(this.colId).then(res => {
                this.data = res;
                this.loading = false;
            });
            }
        },
        loadColumn() {
            var type = this.insColumnDef.typeName;
            var typeName = "init_" + type;
            //在特定的扩展中如果有 init_类型的方法，那么就调用该方法。
            if (this[typeName]) {
                this[typeName]();
            }
            //否则根据栏目ID获取数据。
            else {
                this.loadData();
            }
        },
        getDate(timestamp, format) {
            format = format ? format : "YYYY-MM-DD HH:mm:ss";
            if (timestamp) {
                return moment(timestamp).format(format);
            }
            return "";
        },
        //外部url跳转
        moreOutUrl(url){
            if(url){
                window.open(url);
            }
        },
        //常用应用点击
        handAppClick(commonApp){
            //内部应用
            if(commonApp.type =='interior'){
                if(commonApp.app){
                    var appObj = JSON.parse(commonApp.app);
                    var menu=this.menus.find(item=>{
                        if(item.key ==appObj.value){
                            return item;
                        }
                    })
                    if(menu){
                        this.handClick(menu);
                    }
                }else {
                    this.moreUrl(commonApp.url, false);
                }
            }else if(commonApp.type == 'outside'){
                let state = getState();
                let clientIdJson=commonApp.clientId;
                let clientId;
                if(clientIdJson){
                    clientId=JSON.parse(clientIdJson).value;
                }
                if(!clientId){
                    return;
                }
                getAuthorizeUri(state,clientId,function(authorizeUri){
                    window.open(authorizeUri);
                });
            }else {
                this.moreOutUrl(commonApp.url);
            }

        },
        //删除应用
        handAppDelete(commonApp){
            var self = this;
            this.$confirm({
                title: i18n('msa.delAppInfo','是否删除应用'),
                okText: I18Parse.getI18Val(comLang,'rxForm.ackBtn', '确认'),
                cancelText: I18Parse.getI18Val(comLang,'rxForm.cancelBtn', '取消'),
                onOk(){
                    InsAppCollectApi.del({ids:commonApp.id}).then(res=>{
                        self.loadData();
                    })

                }
            });
        },
        handClick(item) {
            if(item.menuNavType == "2"){//内置微前端打开
                //获取微前端第一个菜单和路由；
                let {firstPath,firstMenu} = this.openFirstFront(item);
                if(!firstMenu){
                    this.$message.error(i18n('msa.noConfMenu','未配置菜单！'));
                    return;
                }
                this.innnerFrontOpen(item,firstPath,firstMenu);
                return ;
            }
            //设置还原window的vue挂载
            if(window.Vue2){
                window.Vue = window.Vue2;
                window.Vue2 = undefined;
            }
            //清除微前端选中；
            this.setActiveFront({})
            //设置是否打开微前端，这里全部给false,当进入微前端时，会在main.js中设置状态;
            this.setOpenFront(false);
            //设置问前端loading状态
            this.setOpenFrontLoading(false);
            //用户开发应用
            if (item.appType == '1' && item.menuNavType == '1') {
                var path = item.appPath ? item.appPath : "/apps";
                window.open(path + "/" + item.key, '_blank');
                return;
            }
            //外部链接情况
            if (item.layout && item.layout == "external") {
                window.open(item.params, '_blank');
                return;
            }
            this.$bus.emit('handUrlClick', item);
            this.handMenuClick(item);
        },
        //添加常用应用
        addCommonApp(){
            var self=this;
            Util.open({
                component: InAppAdd,
                curVm: this,
                title: i18n('addCommonApp','添加常用应用'),
                data:{
                    appType:"custom",
                    appList:this.data,
                    colId:this.colId,
                },
               max:true,
            }, function (action) {
                self.loadData();
            });
        }
    }
});
export {
    loadingComponent,
    customColumnComponet
}
